﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ARD.Common;

namespace SharpObjects.SearchEngine.Common.Indexing
{
    [Serializable]
    public class IndexingHistory
    {
        public IndexingHistory()
        {
            this.HistoryItems = new Dictionary<string, IndexingHistoryItem>();
        }

        public DateTime IndexingStartTime { get; set; }
        public string HistoryFilePath { get; set; }

        public void Load()
        {
            if (System.IO.File.Exists(this.HistoryFilePath))
            {
                this.HistoryItems = (Dictionary<string, IndexingHistoryItem>) FilePersistence.Load(this.HistoryFilePath, null);
            }
        }

        public void Save()
        {
            FilePersistence.Save(this.HistoryItems, this.HistoryFilePath);
        }

        public Dictionary<string, IndexingHistoryItem> HistoryItems { get; set; }

        public void UpdateEntry(string uri, DateTime lastModifiedDate, DateTime lastIndexedDate)
        {
            uri = uri.ToLower();

            lock (this.HistoryItems)
            {
                if (this.HistoryItems.ContainsKey(uri))
                {
                    IndexingHistoryItem historyItem = this.HistoryItems[uri];
                    historyItem.LastModifiedDate = lastModifiedDate;
                    historyItem.IndexedDate = lastIndexedDate;
                }
                else
                {
                    IndexingHistoryItem historyItem = new IndexingHistoryItem() { Uri = uri, LastModifiedDate = lastModifiedDate, IndexedDate = lastIndexedDate };
                    this.HistoryItems.Add(uri, historyItem);
                }
            }
        }

        public void DeleteEntry(string uri)
        {
            uri = uri.ToLower();

            lock(this.HistoryItems)
            {
                if(this.HistoryItems.ContainsKey(uri))
                {
                    this.HistoryItems.Remove(uri);
                }
            }
        }

        public List<string> GetDeleted()
        {
            List<string> deleted = new List<string>();

            var list = from item in this.HistoryItems.Values
                       where item.IndexedDate < this.IndexingStartTime
                       select item.Uri;

            deleted.AddRange(list);

            return deleted;
        }
    }
}
